package util;

import org.apache.commons.beanutils.BeanUtils;
import org.codehaus.jackson.map.util.BeanUtil;

import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JDBCUtil {
    public static Connection getJDBCConnection(String url, String driver) throws ClassNotFoundException, SQLException {

        Class.forName(driver);
        return DriverManager.getConnection(url);

    }


    public static <T> List<T> getQueryList(Connection conn, String sql, Object[] objects, Class<T> clazz) throws Exception {
        PreparedStatement ps = conn.prepareStatement(sql);

        for (int i = 0; objects != null && i < objects.length; i++) {
            ps.setObject(i + 1, objects[i]);
        }
        //得到结果集
        ResultSet resultSet = ps.executeQuery();
        //获取结果集的元数据,并不是说结果集遍历得到每条数据再获取元数据,元数据时结果集的元数据
        ResultSetMetaData metaData = resultSet.getMetaData();
        ArrayList<T> list = new ArrayList<>();
        while (resultSet.next()) {
            //通过元数据获取每条数据的列和值
            T t = clazz.newInstance();
            int columnCount = metaData.getColumnCount();
            for (int i = 0; i < columnCount; i++) {
                //每条数据用T对象封装
                String columnLabel = metaData.getColumnLabel(i + 1);
                //值从结果集中获取
                Object value = resultSet.getObject(columnLabel);
                //通过apache的bean工具类使用反射将属性赋值
                BeanUtils.setProperty(t, columnLabel, value);
            }
            list.add(t);
        }
        return list;
    }
}
